package com.rmondjone.utils

import android.app.Activity
import android.graphics.drawable.Drawable
import android.widget.ImageView
import androidx.annotation.DrawableRes
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.BaseViewHolder


/**
 * copyright：
 * @author：anthui creation date： .
 * @since: 1.0.0
 * @describe:
 */

fun BaseViewHolder.setImage(@IdRes viewId: Int, @DrawableRes resID: Int) {
    getView<ImageView>(viewId).loadImage(resID)
}

fun BaseViewHolder.setImage(@IdRes viewId: Int, url: String) {
    getView<ImageView>(viewId).loadImage(url)
}

fun BaseViewHolder.loadCircleImage(@IdRes viewId: Int, url: String) {
    getView<ImageView>(viewId).loadCircleImage(url)
}

fun BaseViewHolder.loadCircleImage(@IdRes viewId: Int, @DrawableRes resID: Int) {
    getView<ImageView>(viewId).loadCircleImage(resID)
}

fun ImageView.loadImage(@DrawableRes resID: Int, lifecycleOwner: LifecycleOwner? = null) {
    //获取 对应的生命周期
    getGlideRequest(lifecycleOwner)
            .load(resID)
            .into(this)
}

fun ImageView.loadImage(url: String, lifecycleOwner: LifecycleOwner? = null) {
    //获取 对应的生命周期
    getGlideRequest(lifecycleOwner)
            .load(url)
            .into(this)
}

/**
 * copyright：
 * @author：anthui creation date： 2020/11/25.
 * @since: 1.0.0
 * @describe: 加载原型图片
 */
fun ImageView.loadCircleImage(url: String, lifecycleOwner: LifecycleOwner? = null) {
    //获取 对应的生命周期
    getGlideRequest(lifecycleOwner)
            .load(url)
            .applyCircle().into(this)

}

/**
 * copyright：
 * @author：anthui creation date： 2020/11/25.
 * @since: 1.0.0
 * @describe: 加载原型图片
 */
fun ImageView.loadCircleImage(@DrawableRes resId: Int, lifecycleOwner: LifecycleOwner? = null) {

    //获取 对应的生命周期
    getGlideRequest(lifecycleOwner)
            .load(resId)
            .applyCircle().into(this)


}


fun RequestBuilder<Drawable>.applyCircle(): RequestBuilder<Drawable> {

    return this.apply(RequestOptions.bitmapTransform(MultiTransformation(CircleCrop())))
}

/**
 * copyright：
 * @author：anthui creation date： 2020/11/25.
 * @since: 1.0.0
 * @describe:获取上下文对象
 */
private fun ImageView.getGlideRequest(lifecycleOwner: LifecycleOwner? = null): RequestManager {
    //获取 对应的生命周期
    return when (lifecycleOwner) {
        is Activity -> {
            Glide.with(lifecycleOwner)
        }
        is Fragment -> {
            Glide.with(lifecycleOwner)
        }
        else -> {
            Glide.with(context)
        }
    }


}



